import { NextRequest, NextResponse } from 'next/server';

// CORS 配置
const ALLOWED_ORIGINS = [
  'http://localhost:3000',
  'http://localhost:3001',
  'http://localhost:3002',
  'http://127.0.0.1:3000',
  'http://127.0.0.1:3001',
  'http://127.0.0.1:3002',
];

const ALLOWED_METHODS = ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'];
const ALLOWED_HEADERS = [
  'Content-Type',
  'Authorization',
  'X-Requested-With',
  'Accept',
  'Origin',
];

// 添加 CORS 头部到响应
export function addCorsHeaders(response: NextResponse, origin?: string): NextResponse {
  const allowedOrigin = origin && ALLOWED_ORIGINS.includes(origin) ? origin : ALLOWED_ORIGINS[0];
  
  response.headers.set('Access-Control-Allow-Origin', allowedOrigin);
  response.headers.set('Access-Control-Allow-Methods', ALLOWED_METHODS.join(', '));
  response.headers.set('Access-Control-Allow-Headers', ALLOWED_HEADERS.join(', '));
  response.headers.set('Access-Control-Allow-Credentials', 'true');
  response.headers.set('Access-Control-Max-Age', '86400');
  
  return response;
}

// 处理 OPTIONS 预检请求
export function handleOptionsRequest(request: NextRequest): NextResponse {
  const origin = request.headers.get('origin');
  const response = new NextResponse(null, { status: 200 });
  return addCorsHeaders(response, origin || undefined);
}

// CORS 中间件包装器
export function withCors(handler: (request: NextRequest) => Promise<NextResponse>) {
  return async (request: NextRequest): Promise<NextResponse> => {
    const origin = request.headers.get('origin');
    
    // 处理 OPTIONS 预检请求
    if (request.method === 'OPTIONS') {
      return handleOptionsRequest(request);
    }
    
    try {
      // 执行原始处理器
      const response = await handler(request);
      
      // 添加 CORS 头部
      return addCorsHeaders(response, origin || undefined);
    } catch (error) {
      console.error('API 错误:', error);
      const errorResponse = NextResponse.json(
        { error: '服务器内部错误', details: error instanceof Error ? error.message : '未知错误' },
        { status: 500 }
      );
      return addCorsHeaders(errorResponse, origin || undefined);
    }
  };
}
